﻿var pageIndex = 1;
var total = 0;
var pageSize = 10;
var pageCount = 0;
var queryBuilder, ashxParam, columnInfo, addPage, editPage, detailPage;
var selectRows = new Array();

//判断浏览器
var userAgent = navigator.userAgent.toLowerCase();
var browser = {
    version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1],
    safari: /webkit/.test(userAgent),
    opera: /opera/.test(userAgent),
    msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
    mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
};

$(document).ready(function () {
    //禁用右键
    /*  $(document).bind("contextmenu", function (e) {
    return false;
    });
    */
    //设置单条记录的checkbox单击事件
    $("#contentTable").on("click", "input[name='childCheckbox']", function (event) {
        var recordId = $(this).parent().parent().attr("id");
        if (browser.msie)
            recordId = $(this).parent().parent().parent().attr("id");
        if ($(this).prop("checked") == true) {
            $(this).prop("checked", true);
            selectRows.push(recordId);
        }
        else {
            $(this).prop("checked", false);
            if ($.inArray(recordId, selectRows) != -1)
                selectRows.splice($.inArray(recordId, selectRows), 1);

        }
    });

    //checkbox全选
    $("#contentTable").on("click", "input[name='headerCheckbox']", function (event) {

        if ($(this).is(':checked')) {
            $("#contentTable input[name='childCheckbox']").prop("checked", true);
        } else {
            $("#contentTable input[name='childCheckbox']").prop("checked", false);
        }
        var ifChecked = $(this).prop("checked");
        $("#contentTable input[name='childCheckbox']").each(function (i, n) {

            var recordId = $(this).parent().parent().attr("id"); //获取当前主键
            if (browser.msie)
                recordId = $(this).parent().parent().parent().attr("id");
            if (ifChecked == false) {
                if ($.inArray(recordId, selectRows) != -1)
                    selectRows.splice($.inArray(recordId, selectRows), 1);
            }
            else {
                if ($.inArray(recordId, selectRows) == -1)
                    selectRows.push(recordId);
            }
        });
    });
});

function exportExcel(url, formID, controlID, action, iscurrentpage) {
    queryBuilder = $("#" + formID).serializeArray();
    if (url.indexOf('?') > -1) {
        url = url + "&action=" + action + "&pageSize=" + pageSize + "&pageIndex=" + pageIndex + "&isExport=1&isCurrentPage=" + iscurrentpage;
    }
    else {
        url = url + "?action=" + action + "&pageSize=" + pageSize + "&pageIndex=" + pageIndex + "&isExport=1&isCurrentPage=" + iscurrentpage;
    }
    if (queryBuilder != null)
        $.each(queryBuilder, function (i, n) {
            url += "&" + queryBuilder[i].name + "=" + escape(queryBuilder[i].value);
        });
    url = encodeURI(url);
    $("#" + controlID).attr("src", url);
}

function initNewGrid(queryBuilderParam, ashxParamParam, columnInfoParam, addPageParam, editPageParam, detailPageParam) {
    queryBuilder = queryBuilderParam;
    ashxParam = ashxParamParam;
    columnInfo = columnInfoParam;
    addPage = addPageParam;
    editPage = editPageParam;
    detailPage = detailPageParam;
    pageSize = ashxParam.pageSize;
    $("#contentTable").empty();
    //    //初始化表头部分
    //    var header = "";
    //    header = "<tr><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
    //    if (browser.msie)
    //        header = "<tbody><tr><td width=\"50px\" class=\"headerTd\"> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></td>";
    //    for (var i = 0; i < columnInfo.length; i++) {
    //        if (columnInfo[i].width != undefined)
    //            header += "<td class=\"headerTd\" width=\"" + columnInfo[i].width + "\">" + columnInfo[i].columnText + "</td>";
    //        else
    //            header += "<td class=\"headerTd\">" + columnInfo[i].columnText + "</td>";

    //    }
    //    header += "</tr>"; //<td width=\"150px\" class=\"headerTd\">基本操作</td>
    //    if (browser.msie)
    //        header += "</body>";
    //初始化表头部分
    var header = "";
    header = "<thead><tr><th width=\"50px\" class=\"headerTd CheckTD\"  data-noresize> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></th>";
    if (browser.msie)
        header = "<tbody><tr><th width=\"50px\" class=\"headerTd CheckTD\"  data-noresize> <input type=\"checkbox\" name=\"headerCheckbox\" value=\"checkbox\" /></th>";
    for (var i = 0; i < columnInfo.length; i++) {
        if (columnInfo[i].width != undefined)
            header += "<th class=\"headerTd\" width=\"" + columnInfo[i].width + "\"  data-resizable-column-id=\"" + columnInfo[i].columnText + "\">" + columnInfo[i].columnText + "</th>";
        else
            header += "<th class=\"headerTd\" data-resizable-column-id=\"#\">" + columnInfo[i].columnText + "</th>";

    }
    header += "</tr></thead>"; //<td width=\"150px\" class=\"headerTd\">基本操作</td>
    if (browser.msie)
        header += "</body>";


    $("#contentTable").append(header);

    pageClick();
    bindPageButton();


    $("#imgCreate").unbind("click");
    $("#imgCreate").click(function () {
        tb_show(addPageParam.title, addPageParam.url + "?keepThis=true&TB_iframe=true&height=" + addPageParam.height + "&width=" + addPageParam.width, false);
    });
    $("#imgUpdate").unbind("click");
    $("#imgUpdate").click(function () {
        popUpEditPage(editPage);
    });
    $("#imgDelete").unbind("click");
    $("#imgDelete").click(function () {
        deleteRecord(ashxParam);
    });
}

var highlightcolor = '#c1ebff';
//此处clickcolor只能用win系统颜色代码才能成功,如果用#xxxxxx的代码就不行,还没搞清楚为什么:(
var clickcolor = '#51b2f6';
//鼠标移动
function changeto() {
    source = event.srcElement;
    if (source.tagName == "TR" || source.tagName == "TABLE")
        return;
    while (source.tagName != "TD")
        source = source.parentElement;
    source = source.parentElement;
    cs = source.children;
    if (cs[1].style.backgroundColor != highlightcolor && source.id != "nc" && cs[1].style.backgroundColor != clickcolor)
        for (i = 0; i < cs.length; i++) {
            cs[i].style.backgroundColor = highlightcolor;
        }
}
//移动变色
function changeback() {
    source = event.srcElement;
    if (source.tagName == "TR" || source.tagName == "TABLE")
        return;
    while (source.tagName != "TD")
        source = source.parentElement;
    source = source.parentElement;
    cs = source.children;
    if (event.fromElement.contains(event.toElement) || source.contains(event.toElement) || source.id == "nc")
        return
    if (event.toElement != source && cs[1].style.backgroundColor != clickcolor)
        for (i = 0; i < cs.length; i++) {
            cs[i].style.backgroundColor = "";
        }
}
//比如说加单击事件
function clickto() {
    source = event.srcElement;
    if (source.tagName == "TR" || source.tagName == "TABLE")
        return;
    while (source.tagName != "TD")
        source = source.parentElement;
    source = source.parentElement;
    cs = source.children;
    if (cs[1].style.backgroundColor != clickcolor && source.id != "nc")
        for (i = 0; i < cs.length; i++) {
            cs[i].style.backgroundColor = clickcolor;
        }
    else
        for (i = 0; i < cs.length; i++) {
            cs[i].style.backgroundColor = "";
        }
}


function pageClick() {

    if (ashxParam.action == undefined)
        ashxParam.action = "04";
    var submitData = { "action": ashxParam.action, "pageSize": pageSize, "pageIndex": pageIndex };

    //将查询条件和其它请求参数组装
    if (queryBuilder != null)
        $.each(queryBuilder, function (i, n) {
            submitData[queryBuilder[i].name] = queryBuilder[i].value;
        }); else { return; }

    $.ajax({
        type: "post",
        dataType: "json",
        url: ashxParam.url,
        data: submitData,
        success: function (message) {

            total = message.totalCount;
            var data = message.data;
            pageIndex = parseInt(pageIndex);
            $("#contentTable tr").not($("#contentTable tr")[0]).remove();
            if (total == null || data == null) {
                return;
            }

            $.each(data, function (a, n) {

                var row = row = "<tr onSelectStart=\"return false\" ><td class=\"contentTd CheckTD\"><input type=\"checkbox\" name=\"childCheckbox\" value=\"checkbox\" /></td>";
                var col = "";
                var trId = ""//单一记录主键

                if (browser.msie)//IE浏览器需要加上tbody标签，方能动态添加
                    row = "<tbody><tr onSelectStart=\"return false\"><td class=\"contentTd CheckTD\"><input type=\"checkbox\" name=\"childCheckbox\" value=\"checkbox\" /></td>";

                for (var i = 0; i < columnInfo.length; i++) {

                    col = columnInfo[i].columnName;
                    if (columnInfo[i].style != undefined)
                        row += "<td class=\"contentTd\" style=\"" + columnInfo[i].style + "\">"
                    else
                        row += "<td class=\"contentTd\">";
                    if (n[col] == null)
                        row += "</td>";
                    else
                        row += n[col] + "</td>";
                }

                row += "</tr>"; //<td class=\"actionTd\"><span id=\"editAction\" class=\"pointer\"><img src=\"../Images/edt.gif\" width=\"16\" height=\"16\" alt=\"\" />编辑</span>&nbsp;&nbsp;<span class=\"pointer\" id=\"deleteAction\"><img src=\"../Images/del.gif\" width=\"16\" height=\"16\" alt=\"\" />删除</span></td>

                if (browser.msie)
                    row += "</tbody>";

                row = $(row);

                for (var key in n) {
                    trId = n[key];
                    break;
                }

                row.attr("id", trId);

                //行头的checkbox是否选中
                //                if ($.inArray(trId, selectRows) == -1)
                //                    row.find("input[type='checkbox']").removeAttr("checked");
                //                else
                //                    row.find("input[type='checkbox']").attr("checked", "checked");

                //                row.find("#editAction").unbind("click");
                //                row.find("#deleteAction").unbind("click");

                //                row.find("#editAction").click(function () {
                //                    var recordId = row.attr("id");
                //                    popUpEditPage(recordId, editPage);

                //                });
                //                row.find("#deleteAction").click(function () {
                //                    var recordId = row.attr("id");
                //                    deleteRecord(recordId, ashxParam);

                //                });
                row.unbind("dblclick");
                row.dblclick(function () {
                    var recordId = row.attr("id");
                    popUpDetailPage(recordId, detailPage);

                });

                $("#contentTable").append(row);
            });
            //
            selectRows.splice(0, selectRows.length);
            if (total % pageSize == 0)
                pageCount = total / pageSize;
            else
                pageCount = parseInt(total / pageSize) + 1;

            $("#pageCountSpan").text(pageSize);
            $("#totalCountSpan").text(total);
            $("#pageIndexSpan").text(pageIndex + "/" + pageCount);

            //            //判断列头的复选框是否被选择,如果当前页所有的列都被选择,则复选框处于选中状态
            //            var isSelectAll = true;
            //            $("#contentTable input[name='childCheckbox']").each(function (i, n) {
            //                var recordId = $(n).parent().parent().attr("id");
            //                if (browser.msie)
            //                    recordId = $(n).parent().parent().parent().attr("id");
            //                if ($.inArray(recordId, selectRows) == -1)
            //                    isSelectAll = false;
            //            });

            //            if (isSelectAll)
            //                $("#contentTable input[name='headerCheckbox']").attr("checked", "checked");
            //            else
            //                $("#contentTable input[name='headerCheckbox']").removeAttr("checked");

            return false;
        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

//分页按钮
function bindPageButton() {

    $("#firstBut").attr("href", "javascript:void(0)");
    $("#previousBut").attr("href", "javascript:void(0)");
    $("#nextBut").attr("href", "javascript:void(0)");
    $("#lastBut").attr("href", "javascript:void(0)");
    $("#gotoBut").attr("href", "javascript:void(0)");

    $("#firstBut").unbind("click");
    $("#previousBut").unbind("click");
    $("#nextBut").unbind("click");
    $("#lastBut").unbind("click");
    $("#gotoBut").unbind("click");

    //第一页
    $("#firstBut").click(function () {
        if (pageIndex != 1) {
            pageIndex = 1;
            pageClick();
        }
    });

    //上一页
    $("#previousBut").click(function () {
        if (pageIndex != 1) {
            pageIndex--;
            pageClick();
        }
    });


    //最后一页
    $("#lastBut").click(function () {
        if (pageIndex != pageCount) {
            pageIndex = pageCount;
            pageClick();
        }
    });


    //下一页
    $("#nextBut").click(function () {
        if (pageIndex != pageCount) {
            pageIndex++;
            pageClick();
        }
    });


    //跳转到
    $("#gotoBut").click(function () {
        var gotoPage = $("#pagerInput").val();

        var r = /^[0-9]*[1-9][0-9]*$///正整数 

        if (!r.test(gotoPage)) {
            alert("请输入合法数！！！");
            return false;
        }
        if (eval(gotoPage) < 1 || eval(gotoPage) > pageCount) {
            alert("页码超出范围！！！");
            return false;
        }

        var intGotoPage = parseInt(gotoPage);
        pageIndex = intGotoPage;
        pageClick();
        return false;
    });
}


/**
* 
*根据传入表单的ID及请求的服务地址执行表单提交工作,Action为01,执行添加操作
* 
*/
function InitAddPage(formId, ashxUrl) {
    $("#" + formId).validationEngine('attach', {
        promptPosition: "topLeft", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
        //validationEventTriggers: "keyup",
        inlineValidation: false,
        success: false,
        failure: function () {

        },
        onValidationComplete: function (form, status) {
            if (status == true) {
                var formString = $("#" + formId).serialize() + "&action=01";
                $.ajax({
                    type: "post",
                    data: formString,
                    url: ashxUrl,
                    success: function (message) {
                        window.parent.pageClick();
                        window.parent.tb_remove();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                        alert(textStatus);
                    }
                });
            }
        }
    });
}
function InitAddFilePage(formId, ashxUrl) {
    $("#" + formId).validationEngine('attach', {
        promptPosition: "topLeft", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
        //validationEventTriggers: "keyup",
        inlineValidation: false,
        success: false,
        failure: function () {

        },
        onValidationComplete: function (form, status) {
            if (status == true) {
                var options = {
                    type: "POST",
                    url: ashxUrl,
                    data: { "action": "01" },
                    success: function (message) {
                        window.parent.pageClick();
                        window.parent.tb_remove();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                }
                // 将options传给ajaxForm
                $('#' + formId).ajaxSubmit(options);
            }
        }
    });
}

/**
* 
**根据传入的记录ID及请求参数（以JSON对像的形式）执行删除单条记录操作,Action为02。
* 
*/
function deleteRecord(ashxParam) {
    //    if (selectRows.length > 1) {
    //        ymPrompt.errorInfo("选择的记录大于1条，只能选择一条记录！", null, null, null, null);
    //        return false;
    //    }
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要删除选中的记录？', null, null, "删除提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "02" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    var result = eval('(' + data + ')');
                    if (result.ErrorCode == -999) {
                        alert("请先删除附属信息再执行本次操作！");
                    }
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}



/**
* 
*根据传入表单的ID及请求的服务地址执行表单提交工作,Action为03,执行修改操作。
* 
*/

function initEditPage(formId, ashxUrl) {
    var id = request("id");
    //初始化表单标签
    $.ajax({
        async: false,
        type: "post",
        data: { "id": id, "action": "05" },
        dataType: "json",
        url: ashxUrl,
        success: function (data, textStatus) {
            var form = document.forms[formId];
            //遍历指定form表单所有元素
            for (var i = 0; i < form.length; i++) {
                var fieldName = form[i].name;
                var prefix = fieldName.substr(0, 3).toLocaleLowerCase();
                switch (prefix) {
                    case "tex": $("[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    case "sel": $("select[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    case "rad": $("[name='" + fieldName + "'][value='" + data[fieldName.substr(3)] + "']").attr("checked", "checked"); break;
                    case "tet": $("textarea[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    case "ddl": $("select[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                }
            }
        }
        ,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
    $("#" + formId).validationEngine('attach', {
        promptPosition: "topLeft", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
        //validationEventTriggers: "keyup",
        inlineValidation: false,
        success: false,
        failure: function () {

        },

        onValidationComplete: function (form, status) {
            if (status == true) {
                var formString = $("#" + formId).serialize() + "&action=03&id=" + id;
                $.ajax({
                    type: "post",
                    data: formString,
                    url: ashxUrl,
                    success: function (message) {
                        window.parent.pageClick();
                        window.parent.tb_remove();

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                        alert(textStatus);
                    }
                });
            }
        }
    });


}
function initEditFilePage(formId, ashxUrl) {
    var id = request("id");
    //初始化表单标签
    $.ajax({
        async: false,
        type: "post",
        data: { "id": id, "action": "05" },
        dataType: "json",
        url: ashxUrl,
        success: function (data, textStatus) {
            var form = document.forms[formId];
            //遍历指定form表单所有元素
            for (var i = 0; i < form.length; i++) {
                var fieldName = form[i].name;
                var prefix = fieldName.substr(0, 3).toLocaleLowerCase();
                switch (prefix) {
                    case "tex": $("[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    case "sel": $("select[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    case "rad": $("[name='" + fieldName + "'][value='" + data[fieldName.substr(3)] + "']").attr("checked", "checked"); break;
                    case "tet": $("textarea[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    case "ddl": $("select[name='" + fieldName + "']").val(data[fieldName.substr(3)]); break;
                    case "img": $("#" + fieldName).attr("src", data[fieldId.substr(3)]); break;
                }
            }
            $("#" + formId + " img").each(function (i, n) {
                //遍历指定form表单中的所有label标签
                var fieldId = $(n).attr("id");
                var prefix = fieldId.substr(0, 3).toLocaleLowerCase();
                $("#" + fieldId).attr("src", data[fieldId.substr(3)]);
            });
        }
        ,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
    $("#" + formId).validationEngine('attach', {
        promptPosition: "topLeft", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
        //validationEventTriggers: "keyup",
        inlineValidation: false,
        success: false,
        failure: function () {

        },

        onValidationComplete: function (form, status) {
            if (status == true) {
                var options = {
                    type: "POST",
                    url: ashxUrl,
                    data: { "action": "03", "id": id },
                    success: function (message) {
                        window.parent.pageClick();
                        window.parent.tb_remove();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                }
                // 将options传给ajaxForm
                $('#' + formId).ajaxSubmit(options);
            }
        }
    });


}

/**
* 
*根据传入表单的ID及请求服务地址初始化详细信息页面
* 
*/
function initDetailPage(formId, ashxUrl) {
    var id = request("id");
    //初始化表单标签
    $.ajax({
        async: false,
        type: "post",
        data: { "id": id, "action": "05" },
        dataType: "json",
        url: ashxUrl,
        success: function (data, textStatus) {
            $("#" + formId + " label ").each(function (i, n) {
                //遍历指定form表单中的所有label标签
                var fieldId = $(n).attr("id");
                var prefix = fieldId.substr(0, 3).toLocaleLowerCase();
                if (prefix == "img") {
                    $("#" + fieldId).attr("src", data[fieldId.substr(3)]);
                } else {
                    $("#" + fieldId).html(data[fieldId.substr(3)]);
                }
            });
            $("#" + formId + " input ").each(function (i, n) {
                //遍历指定form表单中的所有label标签
                var fieldId = $(n).attr("id");
                if (fieldId != undefined) {
                    var prefix = fieldId.substr(0, 3).toLocaleLowerCase();
                    $("[name='" + fieldId + "']").val(data[fieldId.substr(3)]);
                    // $("#" + fieldId).val(data[fieldId.substr(3)]);
                }
            });

            $("#" + formId + " img").each(function (i, n) {
                //遍历指定form表单中的所有label标签
                var fieldId = $(n).attr("id");
                if (fieldId != undefined) {
                    var prefix = fieldId.substr(0, 3).toLocaleLowerCase();
                    $("#" + fieldId).attr("src", data[fieldId.substr(3)]);
                }
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}


/**
* 
*根据传入表单的ID及请求服务地址初始化详细信息页面
* 
*/
function initDetailsPage(formId, ashxUrl) {
    var id = request("id");
    //初始化表单标签
    $.ajax({
        async: false,
        type: "post",
        data: { "id": id, "action": "08" },
        dataType: "json",
        url: ashxUrl,
        success: function (data, textStatus) {
            $("#" + formId + " label").each(function (i, n) {
                //遍历指定form表单中的所有label标签
                var fieldId = $(n).attr("enventid");
                var prefix = fieldId.substr(0, 3).toLocaleLowerCase();
                if (prefix == "img") {
                    $("#" + fieldId).attr("src", data[fieldId.substr(3)]);
                } else {
                    $("#" + fieldId).html(data[fieldId.substr(3)]);
                }
            });
            $("#" + formId + " img").each(function (i, n) {
                //遍历指定form表单中的所有label标签
                var fieldId = $(n).attr("enventid");
                if (fieldId != undefined) {
                    var prefix = fieldId.substr(0, 3).toLocaleLowerCase();
                    $("#" + fieldId).attr("src", data[fieldId.substr(3)]);
                }
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}


/**
* 
**根据传入的记录ID，及详细页面的信息参数（JSON格式）跳出弹出框，用来查看该条记录的详细信息。
* 
*/
function popUpDetailPage(recordId, detailPage) {
    tb_show(detailPage.title, detailPage.url + "?id=" + recordId + "&keepThis=true&TB_iframe=true&height=" + detailPage.height + "&width=" + detailPage.width, false);
}



/**
* 
**根据传入的记录ID，及编辑页面的信息参数（JSON格式）跳出弹出框，用编辑页面。
* 
*/

function popUpEditPage(editPage) {

    if (selectRows.length > 1) {
        ymPrompt.errorInfo("选择的记录大于1条，只能选择一条记录！", null, null, null, null);
        return false;
    }
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择", null, null, null, null);
        return false;
    }

    tb_show(editPage.title, editPage.url + "?id=" + selectRows[0] + "&keepThis=true&TB_iframe=true&height=" + editPage.height + "&width=" + editPage.width, false);
}

//截取页面传递过来的URL参数
function request(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}


//初始化AutoComplete输入框，第一个参数为输入框的id，第二个参数为隐藏的取value值的id，第三个参数为ajax提交参数，第四个是取的JOSN数据的键
function initAutoComplete(textFieldInputId, valueFieldInputId, ajaxParam, itemParam) {
    var cache = {};

    $("#" + textFieldInputId).unbind("blur"); //失去输入焦点后，如果显示值为空，则同时清空隐藏值
    $("#" + textFieldInputId).bind("blur", function () {

        if ($("#" + textFieldInputId).val() == "") {
            $("#" + textFieldInputId).val("");
            $("#" + valueFieldInputId).val("");
        } else {
            if (($("#" + textFieldInputId).val() in cache) || $("#" + textFieldInputId).val().toString().length == 1)//如果是已经存在缓存中的关键字，也就是输入到文本框中的文字是不能提交的，只能选择后才能提交
            {
                $("#" + textFieldInputId).val("");
                $("#" + valueFieldInputId).val("");
            }
        }
    });

    $("#" + textFieldInputId).autocomplete({
        minLength: 2,
        autoFocus: true,
        source: function (request, response) {
            var term = request.term;
            if (term in cache) {
                response($.map(cache[term], function (item) {
                    return {
                        value: item[itemParam.textField],
                        label: item[itemParam.textField],
                        submitValue: item[itemParam.valueField]
                    }
                }));
                return;
            }
            ajaxParam.data.keywords = request.term;
            $.ajax({
                method: "post",
                url: ajaxParam.url,
                dataType: "json",
                data: ajaxParam.data,
                success: function (data) {
                    cache[term] = data;
                    response($.map(data, function (item) {
                        return {
                            value: item[itemParam.textField],
                            label: item[itemParam.textField],
                            submitValue: item[itemParam.valueField]
                        }
                    }));
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        },
        select: function (e, ui) {
            $("#" + valueFieldInputId).val(ui.item.submitValue);
        }
    });
}


//初始化下拉框
function initDropDownList(selectId, ajaxParam, itemParam) {
    $.ajax({
        method: "post",
        async: false,
        url: ajaxParam.url,
        dataType: "json",
        data: ajaxParam.data,
        success: function (data) {
            $.each(data, function (i, n) {
                $("#" + selectId).append("<option value='" + n[itemParam.valueField] + "'>" + n[itemParam.textField] + "</option>");
            });
        }
    });
}


//初始化查询条件表单
function initQueryBuildForm(formId) {
    $("#" + formId).submit(function (e) {
        pageIndex = 1; //初始化页面索引
        e.preventDefault();
        queryBuilder = $("#" + formId).serializeArray();
        initNewGrid(queryBuilder, ashxParam, columnInfo, addPage, editPage, detailPage);
        return false;
    });
}
/**
* 
**根据传入的记录ID及请求参数（以JSON对像的形式）执行删除单条记录操作,Action为02。
* 
*/
function AuditRecord(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要审核选中的记录？', null, null, "审核提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "AuditRecord" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    var result = eval('(' + data + ')');
                    if (result.ErrorCode == -998) {
                        alert("未回复的信息不能审核！！！");
                    }
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}

function RevocationRecord(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要撤销选中记录的审核？', null, null, "撤销审核提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "RevocationRecord" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    var result = eval('(' + data + ')');
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}

//推送信息
function PushRecords(auditParam) {
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择!", null, null, null, null);
        return false;
    }
    ymPrompt.confirmInfo('确定要推送选中的记录？', null, null, "推送提示", function (tp) {
        if (tp == "ok") {
            $.ajax({
                type: "post",
                data: { "id": selectRows.join(","), "action": "PushRecords" },
                dataType: "text",
                url: ashxParam.url,
                success: function (data) {
                    var result = eval('(' + data + ')');
                    if (result.ErrorCode == -997) {
                        alert("已回复的信息不允许再推送！！！");
                    }
                    pageClick();
                    $("input[name='headerCheckbox']").removeAttr("checked"); //去掉头部的选中
                    //$("tr #" + selectRows[0]).remove(); //确保惟一性 
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
            });
        } else {
            return false;
        }
    });
}

function checkMaxInput(txt, maxLen) {
    if (txt.value.length > maxLen) // if too long.... trim it! 
        txt.value = txt.value.substring(0, maxLen); // otherwise, update 'characters left' counter 
    //else document.getElementById('remLen').innerText = maxLen - form.txtContent.value.length; 
}



function ShowRecord() {
    if (selectRows.length > 1) {
        ymPrompt.errorInfo("选择的记录大于1条，只能选择一条记录！", null, null, null, null);
        return false;
    }
    if (selectRows.length == 0) {
        ymPrompt.errorInfo("你没有选择任何记录！请选择", null, null, null, null);
        return false;
    }
    popUpDetailPage(selectRows[0], detailPage);
}
